let _Vue = null;
export default class VueRouter {
  static install(Vue) {
    if (VueRouter.install.installed) {
      return;
    }
    VueRouter.install.installed = true;

    _Vue = Vue;

    _Vue.mixin({
      beforeCreate() {
        if (this.$options.router) {
          _Vue.prototype.$router = this.$options.router;
        }
      },
    });
  }

  constructor(options) {
    this.options = options;
    this.routeMap = {};
    this.mode = this.options.mode || 'history';
    this.data = _Vue.observable({
      current: '/',
    });
    this.init();
    this.initEvent();
  }

  init() {
    this.createRouteMap();
    this.initComponent(_Vue);
  }

  createRouteMap() {
    this.options.routes.forEach((route) => {
      this.routeMap[route.path] = route.component;
    });
  }

  initComponent(Vue) {
    const self = this;

    Vue.component('router-link', {
      props: {
        to: String,
      },
      render(h) {
        return h('a', {
          attrs: {
            href: this.to,
          },
          on: {
            click: this.clickHandler,
          },
        }, [this.$slots.default]);
      },
      methods: {
        clickHandler(e) {
          if (self.mode === 'hash') {
            window.location.hash = this.to;
          } else {
            history.pushState({}, '', this.to);
            this.$router.data.current = this.to;
          }
          e.preventDefault();
        },
      },
    });

    Vue.component('router-view', {
      render(h) {
        const component = self.routeMap[self.data.current]
        return h(component);
      }
    })
  }

  initEvent() {
    if (this.mode === 'hash') {
      window.addEventListener('hashchange', () => {
        this.data.current = window.location.hash.split('#')[1];
      });
    } else {
      window.addEventListener('popstate', () => {
        this.data.current = window.location.pathname;
      });
    }
  }
}
